<template>
    <div class="container">
        <Breadcrumb :items="['menu.report', 'menu.report.recharge']" />
        <a-card class="general-card" :title="$t('recharge.list')">
            <a-row>
                <a-col :flex="1">
                    <a-form
                        :model="formModel"
                        :label-col-props="{ span: 6 }"
                        :wrapper-col-props="{ span: 18 }"
                        label-align="left"
                    >
                        <a-row :gutter="16">
                            <a-col :span="6">
                                <a-form-item
                                    field="cardNumber"
                                    :label="$t('recharge.cardNumber')"
                                >
                                    <a-input
                                        v-model="formModel.cardNumber"
                                        :placeholder="
                                            $t('input.placeholder') +
                                            $t('recharge.cardNumber')
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item
                                    field="time"
                                    :label="$t('recharge.createTime')"
                                >
                                    <a-range-picker
                                        v-model="formModel.time"
                                        show-time
                                        :time-picker-props="{
                                            defaultValue: [
                                                '00:00:00',
                                                '00:00:00',
                                            ],
                                        }"
                                        style="width: 100%"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="5">
                                <a-form-item
                                    field="userType"
                                    :label="$t('recharge.userType')"
                                >
                                    <a-select
                                        v-model="formModel.userType"
                                        style="width: 200px"
                                        :placeholder="
                                            $t(
                                                $t('select.placeholder') +
                                                    $t('recharge.userType')
                                            )
                                        "
                                    >
                                        <a-option
                                            v-for="item in userTypeOptions"
                                            :key="item.value"
                                            :value="item.value"
                                            :label="item.label"
                                        ></a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="5">
                                <a-form-item
                                    field="chanel"
                                    :label="$t('recharge.chanel')"
                                >
                                    <a-select
                                        v-model="formModel.channel"
                                        style="width: 200px"
                                        :placeholder="
                                            $t(
                                                $t('select.placeholder') +
                                                    $t('recharge.chanel')
                                            )
                                        "
                                    >
                                        <a-option
                                            v-for="item in chanelOptions"
                                            :key="item.value"
                                            :value="item.value"
                                            :label="item.label"
                                        ></a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="fuelCode"
                                    :label="
                                        $t('order.form.cheduiId.placeholder')
                                    "
                                >
                                    <a-select
                                        v-model="formModel.companyId"
                                        allow-clear
                                        style="width: 240px"
                                        :placeholder="
                                            $t(
                                                'order.form.cheduiId.placeholder'
                                            )
                                        "
                                    >
                                        <a-option
                                            v-for="item in cheduiList"
                                            :key="item.companyId"
                                            :value="item.companyId"
                                            :label="item.companyName"
                                        ></a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="customerId"
                                    :label="
                                        $t('order.form.customerId.placeholder')
                                    "
                                >
                                    <a-select
                                        v-model="formModel.customerId"
                                        :style="{ width: '180px' }"
                                        placeholder="选择会员"
                                        allow-search
                                        allow-clear
                                    >
                                        <template
                                            v-for="item in vipSelects"
                                            :key="item.customerId"
                                        >
                                            <a-option
                                                :value="item.customerId"
                                                >{{
                                                    item.customerName
                                                }}</a-option
                                            >
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider style="height: 84px" direction="vertical" />
                <a-col :flex="'86px'" style="text-align: right">
                    <a-space direction="vertical" :size="18">
                        <a-button type="primary" @click="search(1)">
                            <template #icon>
                                <icon-search />
                            </template>
                            {{ $t('search') }}
                        </a-button>
                        <a-button type="primary" @click="exportExcel()">
                            <template #icon>
                                <icon-download />
                            </template>
                            {{ $t('search.form.export') }}
                        </a-button>
                        <a-button @click="reset">
                            <template #icon>
                                <icon-refresh />
                            </template>
                            {{ $t('reset') }}
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
            <a-divider style="margin-top: 0" />
            <a-row style="margin-bottom: 16px">
                <a-col
                    :span="12"
                    style="
                        display: flex;
                        align-items: center;
                        justify-content: end;
                    "
                >
                    <a-tooltip :content="$t('refresh')">
                        <div class="action-icon" @click="() => search()">
                            <icon-refresh size="18" />
                        </div>
                    </a-tooltip>
                    <a-tooltip :content="$t('table.column.setting')">
                        <a-popover
                            trigger="click"
                            position="bl"
                            @popup-visible-change="popupVisibleChange"
                        >
                            <div class="action-icon"
                                ><icon-settings size="18"
                            /></div>
                            <template #content>
                                <div id="tableSetting">
                                    <div
                                        v-for="(item, index) in showColumns"
                                        :key="item.dataIndex"
                                        class="setting"
                                    >
                                        <div
                                            style="
                                                margin-right: 4px;
                                                cursor: move;
                                            "
                                        >
                                            <icon-drag-arrow />
                                        </div>
                                        <div>
                                            <a-checkbox
                                                v-model="item.checked"
                                                @change="
                                                    handleChange(
                                                        $event,
                                                        item as TableColumnData,
                                                        index
                                                    )
                                                "
                                            >
                                            </a-checkbox>
                                        </div>
                                        <div class="title">
                                            {{
                                                item.title === '#'
                                                    ? '序列号'
                                                    : item.title
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </a-popover>
                    </a-tooltip>
                </a-col>
            </a-row>
            <a-table
                row-key="id"
                :loading="loading"
                :pagination="pagination"
                :columns="(cloneColumns as TableColumnData[])"
                :data="renderData"
                :bordered="false"
                :size="size"
                @page-change="onPageChange"
            >
            </a-table>
        </a-card>
    </div>
</template>

<script lang="ts" setup>
    import { computed, ref, reactive, watch, nextTick } from 'vue';
    // import { useRouter } from 'vue-router';
    import { useI18n } from 'vue-i18n';
    import moment from 'moment';
    import useLoading from '@/hooks/loading';
    import qee from 'qf-export-excel';
    import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
    import cloneDeep from 'lodash/cloneDeep';
    import pick from 'lodash/pick';
    import Sortable from 'sortablejs';
    import i18n from '@/locale';
    import { getList, del, getPageType, getCheduiList } from './service';
    import { userTypeOptions, chanelOptions } from './const';

    type SizeProps = 'mini' | 'small' | 'medium' | 'large';
    type Column = TableColumnData & { checked?: true };

    const generateFormModel = () => {
        return {
            companyId: '',
            customerId: '',
            time: [
                moment(new Date()).format('YYYY-MM-DD 00:00:00'),
                moment(new Date()).format('YYYY-MM-DD 23:59:59'),
            ],
            status: '',
        };
    };
    const { loading, setLoading } = useLoading(true);
    const { t } = useI18n();
    const renderData = ref<any[]>([]);
    const renderExcelData = ref<any[]>([]);
    const formModel = ref(generateFormModel());
    const cloneColumns = ref<Column[]>([]);
    const showColumns = ref<Column[]>([]);
    const cheduiList = ref<any[]>([]);
    const vipSelects = ref<any[]>([]);
    const payTypeList = ref<any[]>([]);

    const size = ref<SizeProps>('medium');
    // const payTypeData: any = getPageType();
    const pagination = reactive({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const columns = computed<TableColumnData[]>(() => [
        {
            title: t('order.stationName'),
            dataIndex: 'stationName',
            width: 120,
        },
        {
            title: t('recharge.cardNumber'),
            dataIndex: 'cardNumber',
            width: 120,
        },
        {
            title: t('recharge.chanel'),
            dataIndex: 'chanel',
            width: 110,
            render({ record }) {
                return (
                    {
                        1: t('recharge.stk'),
                        2: t('recharge.xnk'),
                    } as any
                )[record.chanel];
            },
        },
        {
            title: t('recharge.userType'),
            dataIndex: 'userType',
            width: 110,
            render({ record }) {
                return (
                    {
                        1: t('recharge.yh'),
                        2: t('recharge.cd'),
                        3: t('recharge.yg'),
                        4: t('recharge.cdsj'),
                    } as any
                )[record.userType];
            },
        },
        {
            title: t('recharge.totalAmount'),
            dataIndex: 'totalAmount',
            width: 110,
        },
        {
            title: t('recharge.realAmount'),
            dataIndex: 'realAmount',
            width: 120,
        },
        {
            title: t('recharge.payType'),
            dataIndex: 'payName',
            width: 120,
        },
        {
            title: t('recharge.createTime'),
            dataIndex: 'createTime',
            width: 120,
        },
    ]);

    const columnsExcel = computed<TableColumnData[]>(() => [
        {
            title: t('recharge.cardNumber'),
            key: 'cardNumber',
        },
        {
            title: t('recharge.chanel'),
            key: 'chanel',
            render({ record }) {
                return (
                    {
                        1: t('recharge.stk'),
                        2: t('recharge.xnk'),
                    } as any
                )[record.chanel];
            },
        },
        {
            title: t('recharge.userType'),
            key: 'userType',
            render({ record }) {
                return (
                    {
                        1: t('recharge.yh'),
                        2: t('recharge.cd'),
                        3: t('recharge.yg'),
                        4: t('recharge.cdsj'),
                    } as any
                )[record.userType];
            },
        },
        {
            title: t('recharge.totalAmount'),
            key: 'totalAmount',
        },
        {
            title: t('recharge.realAmount'),
            key: 'realAmount',
        },
        {
            title: t('recharge.payType'),
            key: 'payName',
        },
        {
            title: t('recharge.createTime'),
            key: 'createTime',
        },
    ]);

    const fetchData = async (params: any) => {
        setLoading(true);
        try {
            const data = await getList(params);
            // const payTypeData: any = await getPageType();
            const payTypeEnum = (payTypeList.value || []).reduce(
                (res: any, item: any) => {
                    res[item.payId] = item[i18n.global.t('payType')];
                    return res;
                },
                {} as any
            );

            renderData.value = (data.result.records || []).map((item: any) => {
                return {
                    ...item,
                    payName: payTypeEnum[item.payType],
                };
            });

            pagination.current = params.current;
            pagination.total = data.result.total;
        } finally {
            setLoading(false);
        }
    };

    const search = (pageNum?: number) => {
        if (formModel.value.time) {
            formModel.value.beginTime = formModel.value.time
                ? formModel.value.time[0]
                : '';
            formModel.value.endTime = formModel.value.time
                ? formModel.value.time[1]
                : '';
        } else {
            formModel.value.beginTime = '';
            formModel.value.endTime = '';
        }
        fetchData({
            ...formModel.value,
            current: pageNum || pagination.current,
            size: pagination.pageSize,
        });
    };
    const onPageChange = (pageNum: number) => {
        pagination.current = pageNum;

        fetchData({
            ...formModel.value,
            size: pagination.pageSize,
            current: pageNum,
        });
    };
    search(1);

    const getCheduiListDtat = async () => {
        const data = await getCheduiList();
        cheduiList.value = data?.result.company || [];
        vipSelects.value = data?.result.customer || [];
    };
    getCheduiListDtat();

    const getPayTypeNameData = async () => {
        // const data = await getCheduiList();
        const data = await getPageType();

        // formModel.value.fuelCode = data?.result?.[0]?.fuelId;
        payTypeList.value = data?.result || [];
    };
    getPayTypeNameData();

    const exportExcel = async (pageNum?: number) => {
        setLoading(true);
        if (formModel.value.time) {
            formModel.value.beginTime = formModel.value.time
                ? formModel.value.time[0]
                : '';
            formModel.value.endTime = formModel.value.time
                ? formModel.value.time[1]
                : '';
        }
        console.log('formModel.time.value', pagination);
        //    delete formModel.value.time;

        // const payTypeData: any = getPageType();
        //   获取total
        const data = await getList({
            ...formModel.value,
            current: pageNum || pagination.current,
            size: pagination.pageSize,
        });
        //   根据total,查询所有的数据
        console.log(data.result.total);
        const dataEnd = await getList({
            ...formModel.value,
            current: 1,
            size: data.result.total,
        });
        renderExcelData.value = dataEnd.result.records || [];
        console.log(renderExcelData.value);

        const payTypeEnum = (payTypeList.value || []).reduce(
            (res: any, item1: any) => {
                res[item1.payId] = item1[i18n.global.t('payType')];
                return res;
            },
            {} as any
        );

        renderExcelData.value.forEach((item, index, arr) => {
            if (item.chanel === 1) {
                item.chanel = t('recharge.stk');
            } else {
                item.chanel = t('recharge.xnk');
            }
            if (item.userType === 1) {
                item.userType = t('recharge.yh');
            } else if (item.userType === 2) {
                item.userType = t('recharge.cd');
            } else if (item.userType === 3) {
                item.userType = t('recharge.yg');
            } else if (item.userType === 4) {
                item.userType = t('recharge.cdsj');
            }

            item.payName = payTypeEnum[item.payType];
        });

        setLoading(false);
        qee(
            columnsExcel.value,
            renderExcelData.value,
            `${'储值报表'}${formModel.value.time[0].valueOf()}${'--'}${formModel.value.time[1].valueOf()}`
        );
    };

    const reset = () => {
        formModel.value = generateFormModel();
        search(1);
    };

    const handleChange = (
        checked: boolean | (string | boolean | number)[],
        column: Column,
        index: number
    ) => {
        if (!checked) {
            cloneColumns.value = showColumns.value
                .filter((item) => item.checked)
                .filter((item) => item.dataIndex !== column.dataIndex);
        } else {
            cloneColumns.value.splice(index, 0, column);
        }
    };

    const exchangeArray = <T extends Array<any>>(
        array: T,
        beforeIdx: number,
        newIdx: number,
        isDeep = false
    ): T => {
        const newArray = isDeep ? cloneDeep(array) : array;
        if (beforeIdx > -1 && newIdx > -1) {
            // 先替换后面的，然后拿到替换的结果替换前面的
            newArray.splice(
                beforeIdx,
                1,
                newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
            );
        }
        return newArray;
    };

    const popupVisibleChange = (val: boolean) => {
        if (val) {
            nextTick(() => {
                const el = document.getElementById(
                    'tableSetting'
                ) as HTMLElement;
                const sortable = new Sortable(el, {
                    onEnd(e: any) {
                        const { oldIndex, newIndex } = e;
                        exchangeArray(cloneColumns.value, oldIndex, newIndex);
                        exchangeArray(showColumns.value, oldIndex, newIndex);
                    },
                });
            });
        }
    };

    watch(
        () => columns.value,
        (val) => {
            cloneColumns.value = cloneDeep(val);
            cloneColumns.value.forEach((item, index) => {
                item.checked = true;
            });
            showColumns.value = cloneDeep(cloneColumns.value);
        },
        { deep: true, immediate: true }
    );
</script>

<style scoped lang="less">
    .container {
        padding: 0 20px 20px;
    }

    :deep(.arco-table-th) {
        &:last-child {
            .arco-table-th-item-title {
                margin-left: 16px;
            }
        }
    }

    .action-icon {
        margin-left: 12px;
        cursor: pointer;
    }

    .active {
        color: #0960bd;
        background-color: #e3f4fc;
    }

    .setting {
        display: flex;
        align-items: center;
        width: 200px;

        .title {
            margin-left: 12px;
            cursor: pointer;
        }
    }
</style>

<style lang="less">
    .arco-dropdown-open .arco-icon-down {
        transform: rotate(180deg);
    }
</style>
